<template>
  <view v-if="visible" class="modal-overlay" @click="closeModal">
    <view class="modal-content" @click.stop>
      <view class="modal-header">
        <text class="modal-title">智能课程生成</text>
        <uni-icons type="closeempty" size="24" @click="closeModal" />
      </view>

      <scroll-view scroll-y class="modal-body">
        <!-- 生成选项 -->
        <view class="options-section">
          <text class="section-title">生成选项</text>

          <view class="form-group">
            <text class="label">选择教师</text>
            <picker
              :value="selectedTeacherIndex"
              :range="teacherOptions"
              range-key="name"
              @change="onTeacherSelect"
              class="picker"
            >
              <view class="picker-text">
                {{ selectedTeacher?.name || '请选择教师' }}
              </view>
            </picker>
          </view>

          <view class="form-group">
            <text class="label">课程科目</text>
            <picker
              :value="selectedSubjectIndex"
              :range="subjectOptions"
              @change="onSubjectSelect"
              class="picker"
            >
              <view class="picker-text">
                {{ selectedSubject || '请选择科目' }}
              </view>
            </picker>
          </view>

          <view class="form-group">
            <text class="label">生成策略</text>
            <radio-group @change="onStrategyChange" class="radio-group">
              <label class="radio-item">
                <radio value="pattern" :checked="strategy === 'pattern'" />
                <text>基于历史模式</text>
              </label>
              <label class="radio-item">
                <radio value="fill" :checked="strategy === 'fill'" />
                <text>填充空闲时段</text>
              </label>
            </radio-group>
          </view>

          <view class="form-group">
            <text class="label">课程数量</text>
            <slider
              :value="courseCount"
              @change="onCountChange"
              :min="1"
              :max="10"
              show-value
              class="slider"
            />
          </view>
        </view>

        <!-- 预览结果 -->
        <view v-if="generatedSchedules.length > 0" class="preview-section">
          <text class="section-title">预览结果</text>

          <view class="schedule-list">
            <view
              v-for="(schedule, index) in generatedSchedules"
              :key="index"
              class="schedule-item"
            >
              <view class="schedule-info">
                <text class="schedule-title">{{ schedule.subjectName }}</text>
                <text class="schedule-time">
                  {{ formatDateTime(schedule.startDatetime) }}
                </text>
                <text class="schedule-teacher">{{ schedule.teacherName }}</text>
              </view>
              <switch
                :checked="schedule.selected"
                @change="(e) => toggleSchedule(index, e.detail.value)"
                color="#2979ff"
              />
            </view>
          </view>

          <view class="conflict-warning" v-if="hasConflicts">
            <uni-icons type="warning" size="16" color="#ff4d4f" />
            <text>检测到时间冲突，请调整选择</text>
          </view>
        </view>
      </scroll-view>

      <view class="modal-footer">
        <button class="btn-cancel" @click="closeModal">取消</button>
        <button class="btn-confirm" @click="confirmGenerate" :disabled="!canGenerate">
          确认生成 ({{ selectedCount }}个)
        </button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import type { ScheduleItem, SmartScheduleSuggestion } from '@/types/schedule'
import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue'

const props = defineProps<{
  visible: boolean
  suggestions: SmartScheduleSuggestion[]
}>()

const emit = defineEmits<{
  'update:visible': [value: boolean]
  generate: [schedules: ScheduleItem[]]
}>()

// 状态管理
const selectedTeacherIndex = ref(0)
const selectedSubjectIndex = ref(0)
const courseCount = ref(3)
const strategy = ref<'pattern' | 'fill'>('pattern')
const generatedSchedules = ref<ScheduleItem[]>([])

// 选项数据
const teacherOptions = ref([
  { id: '1', name: '张老师' },
  { id: '2', name: '李老师' },
  { id: '3', name: '王老师' },
])

const subjectOptions = ref(['数学', '英语', '物理', '化学', '语文'])

const selectedTeacher = computed(() => teacherOptions.value[selectedTeacherIndex.value])
const selectedSubject = computed(() => subjectOptions.value[selectedSubjectIndex.value])

const hasConflicts = computed(() =>
  generatedSchedules.value.some((s) => s.conflicts && s.conflicts.length > 0),
)

const selectedCount = computed(() => generatedSchedules.value.filter((s) => s.selected).length)

const canGenerate = computed(() => selectedCount.value > 0 && !hasConflicts.value)

// 生成课程
const generateSchedules = () => {
  if (!selectedTeacher.value || !selectedSubject.value) return

  const schedules: ScheduleItem[] = []
  const now = new Date()
  const monday = new Date(now)
  monday.setDate(now.getDate() - (now.getDay() || 7) + 1)

  // 基于策略生成
  if (strategy.value === 'pattern') {
    // 基于历史模式
    const suggestion = props.suggestions.find((s) => s.teacherId === selectedTeacher.value.id)
    const recommendations = suggestion?.recommendations || []

    for (let i = 0; i < Math.min(courseCount.value, recommendations.length); i++) {
      const rec = recommendations[i]
      const date = new Date(monday)
      date.setDate(monday.getDate() + rec.dayOfWeek)

      schedules.push({
        id: Date.now() + i,
        subjectName: selectedSubject.value,
        teacherName: selectedTeacher.value.name,
        teacherId: selectedTeacher.value.id,
        classRoomName: '自动分配教室',
        classRoomId: 1,
        startDatetime: `${date.toISOString().split('T')[0]} ${rec.startTime}`,
        endDatetime: `${date.toISOString().split('T')[0]} ${rec.endTime}`,
        studentNum: 0,
        color: '#2979ff',
      })
    }
  } else {
    // 填充空闲时段
    for (let i = 0; i < courseCount.value; i++) {
      const date = new Date(monday)
      date.setDate(monday.getDate() + (i % 7))
      const hour = 9 + Math.floor(i / 7) * 2

      schedules.push({
        id: Date.now() + i,
        subjectName: selectedSubject.value,
        teacherName: selectedTeacher.value.name,
        teacherId: selectedTeacher.value.id,
        classRoomName: '自动分配教室',
        classRoomId: 1,
        startDatetime: `${date.toISOString().split('T')[0]} ${hour.toString().padStart(2, '0')}:00`,
        endDatetime: `${date.toISOString().split('T')[0]} ${(hour + 1)
          .toString()
          .padStart(2, '0')}:00`,
        studentNum: 0,
        color: '#52c41a',
      })
    }
  }

  // 添加选中状态
  generatedSchedules.value = schedules.map((s) => ({
    ...s,
    selected: true,
  }))
}

const formatDateTime = (datetime: string) => {
  const date = new Date(datetime)
  const day = date.getDay()
  const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  return `${weekdays[day]} ${date.getHours()}:00-${date.getHours() + 1}:00`
}

const toggleSchedule = (index: number, selected: boolean) => {
  generatedSchedules.value[index].selected = selected
}

const onTeacherSelect = (e: any) => {
  selectedTeacherIndex.value = e.detail.value
  generateSchedules()
}

const onSubjectSelect = (e: any) => {
  selectedSubjectIndex.value = e.detail.value
  generateSchedules()
}

const onCountChange = (e: any) => {
  courseCount.value = e.detail.value
  generateSchedules()
}

const onStrategyChange = (e: any) => {
  strategy.value = e.detail.value as 'pattern' | 'fill'
  generateSchedules()
}

const confirmGenerate = () => {
  const selectedSchedules = generatedSchedules.value.filter((s) => s.selected)
  emit('generate', selectedSchedules)
  closeModal()
}

const closeModal = () => {
  emit('update:visible', false)
  generatedSchedules.value = []
}

// 监听参数变化，重新生成
watch([selectedTeacherIndex, selectedSubjectIndex, courseCount, strategy], () => {
  generateSchedules()
})

// 初始化
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      generateSchedules()
    }
  },
)
</script>

<style scoped lang="scss">
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 20rpx;
  width: 90%;
  max-width: 600rpx;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid $border-color;
}

.modal-title {
  font-size: 32rpx;
  font-weight: 600;
  color: $text-main;
}

.modal-body {
  flex: 1;
  padding: 30rpx;
}

.options-section,
.preview-section {
  margin-bottom: 40rpx;
}

.section-title {
  font-size: 28rpx;
  font-weight: 600;
  color: $text-main;
  margin-bottom: 20rpx;
}

.form-group {
  margin-bottom: 30rpx;
}

.label {
  display: block;
  font-size: 28rpx;
  color: $text-main;
  margin-bottom: 10rpx;
  font-weight: 500;
}

.picker {
  width: 100%;
}

.picker-text {
  padding: 20rpx;
  border: 1rpx solid $border-color;
  border-radius: 10rpx;
  font-size: 28rpx;
  color: $text-main;
}

.radio-group {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  gap: 20rpx;
  font-size: 28rpx;
  color: $text-main;
}

.slider {
  margin: 20rpx 0;
}

.schedule-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.schedule-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
}

.schedule-info {
  flex: 1;
}

.schedule-title {
  display: block;
  font-size: 28rpx;
  font-weight: 600;
  color: $text-main;
}

.schedule-time {
  display: block;
  font-size: 24rpx;
  color: $text-secondary;
  margin: 5rpx 0;
}

.schedule-teacher {
  display: block;
  font-size: 24rpx;
  color: $text-secondary;
}

.conflict-warning {
  display: flex;
  align-items: center;
  gap: 10rpx;
  margin-top: 20rpx;
  padding: 20rpx;
  background-color: rgba(255, 77, 79, 0.1);
  border-radius: 10rpx;
  color: #ff4d4f;
  font-size: 26rpx;
}

.modal-footer {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid $border-color;
}

.btn-cancel,
.btn-confirm {
  flex: 1;
  padding: 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
}

.btn-cancel {
  background-color: #f5f5f5;
  color: $text-main;
}

.btn-confirm {
  background-color: $primary-color;
  color: white;

  &:disabled {
    background-color: #d9d9d9;
    color: #bfbfbf;
  }
}
</style>
